import { defineStore } from 'pinia';
import { Session } from '@/utils';
import { useRouterPush } from '@/composables';
import { useRouteStore } from '../route';
import API from '@/api';

interface AuthState {
    /** 用户信息 */
    userInfo: Auth.UserInfo;
    /** 用户token */
    token: string;
    /** 登录的加载状态 */
    loginLoading: boolean;
}

export const useAuthStore = defineStore('auth-store', {
    state: (): AuthState => ({
        userInfo: Session.get('userInfo') || {},
        token: Session.get('token'),
        loginLoading: false
    }),
    getters: {
        /** 是否登录 */
        isLogin(state) {
            return Boolean(state.token);
        }
    },
    actions: {
        /** 重置auth状态 */
        resetAuthStore() {
            const { toLogin } = useRouterPush(false);
            const { resetRouteStore } = useRouteStore();
            Session.clear();
            this.$reset();
            resetRouteStore();
            toLogin();
        },
        /**
         * 登录
         * @param userName - 用户名
         * @param password - 密码
         */

        async login(datas: object) {
            this.loginLoading = true;
            const resp = await API.user_login({ data: datas, method: 'POST' });
            if (resp) {
                Session.set('token', resp.token);
                await this.userInfo();
            }
            this.loginLoading = false;
        },
        /**
         *  获取用户信息
         *
         */
        async userInfo() {
            const { toLoginRedirect } = useRouterPush(false);
            const res = await API.login_userInfo({ method: 'GET' });
            if (res) {
                Session.set('userInfo', res);
                toLoginRedirect();
            }
        }
    }
});
